package com.xiaouyudeguang.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xiaouyudeguang.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.context.SecurityContextHolder;

import java.time.LocalDateTime;

@Configuration
@ConditionalOnClass(SecurityContextHolder.class)
public class MybatisMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        String userId = null;
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            userId = "system";
        }
        this.setFieldValByName("creator", userId, metaObject);
        this.setFieldValByName("created", LocalDateTime.now(), metaObject);
        this.setFieldValByName("modifier", userId, metaObject);
        this.setFieldValByName("modified", LocalDateTime.now(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userId = null;
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            userId = "system";
        }
        this.setFieldValByName("modifier", userId, metaObject);
        this.setFieldValByName("modified", LocalDateTime.now(), metaObject);
    }

}
